package com.david.musicapp.activity

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.david.core.utils.PermissionUtils
import com.david.musicapp.MusicApplication
import com.david.musicapp.utils.SongHelper

open class BaseActivity:AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (!PermissionUtils.checkPermissions(this, Manifest.permission.READ_MEDIA_AUDIO)) {
                PermissionUtils.requestPermissionsResult(this, 0, arrayOf(Manifest.permission.READ_MEDIA_AUDIO),
                    object : PermissionUtils.OnPermissionListener {
                        override fun onPermissionDenied() {
                            Toast.makeText(MusicApplication.instance(), "请先打开读取存储权限", Toast.LENGTH_SHORT).show()
                            onPermissionDenied(Manifest.permission.READ_MEDIA_AUDIO)
                        }

                        override fun onPermissionGranted() {
                            onPermissionGranted(Manifest.permission.READ_MEDIA_AUDIO)
                        }
                    })
            } else {
                SongHelper.getInstance().refreshList()
            }
        } else {
            if (!PermissionUtils.checkPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                PermissionUtils.requestPermissionsResult(this, 0, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    object : PermissionUtils.OnPermissionListener {
                        override fun onPermissionDenied() {
                            Toast.makeText(MusicApplication.instance(), "请先打开读取存储权限", Toast.LENGTH_SHORT).show()
                            onPermissionDenied(Manifest.permission.READ_EXTERNAL_STORAGE)
                        }

                        override fun onPermissionGranted() {
                            onPermissionGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
                        }
                    })
            } else {
                SongHelper.getInstance().refreshList()
            }
        }
    }

    fun requestPermission(permissions: Array<String>){
        PermissionUtils.requestPermissionsResult(this, 0, permissions,
            object : PermissionUtils.OnPermissionListener {
                override fun onPermissionDenied() {
                    for (item in permissions) {
                        onPermissionDenied(item)
                    }
                }

                override fun onPermissionGranted() {
                    for (item in permissions) {
                        onPermissionGranted(item)
                    }
                }
            })
    }

    open fun onPermissionGranted(permission:String){

    }

    open fun onPermissionDenied(permission:String){

    }
}